#!/usr/bin/python

if __name__=='__main__':
    

from exception.excetion_exec import excetion_exec
import string
import sys
import subprocess
import os

CUR_PARENT=1
INIT_PARENT=2

class exec_base(object):
    def __init__(self, BG=None, command=None, parent=INIT_PARENT
            stdin=None, stdout=None, stderr=None, dir=None):
        self.__bg = BG
        self.__command = command
        self.__parent = parent
        self.__stdin = stdin
        self.__stdout = stdout
        self.__stderr = stderr
        if None!=dir:
            self.__dir = dir
        else:
            self.__dir = os.getcwd()

    def exec(command=None):
        if None!=command:
            self.__command = command
        if False==isinstance(self.__command, list):
            raise excetion_exec('command want to exec is valid!')
        
        if True==self.__bg:
            self.__command.append('&')
        fork_to_exec = False
        if INIT_PARENT==self.__parent:
            fork_to_exec = True
        elif CUR_PARENT==self.__parent:
            fork_to_exec = False

        if True==fork_to_exec:
            pid = -1
            pid = fork()
            if 0==pid:
            #child process
                try:
                    subprocess.Popen(self.__command, cwd=self.__dir, stdin=self.__stdin, stdout=self.__stdout,
                            stderr=self.__stderr).wait()
                except OSError, e:
                    raise excetion_exec(e.strerror)
                finally:
                    os.exit(0)
            else:#parent process
            #because the argument parent = init. so just exit the parent.
            #the system kernel will make the init to become the parent of child process
                sys.exit(0)

        else:
            try:
                subprocess.Popen(self.__command, cwd=self.__dir, stdin=self.__stdin, stdout=self.__stdout,
                            stderr=self.__stderr).wait()
            except OSError, e:
                raise excetion_exec(e.strerror)

        return None

    def get_command():
        return self.__command
